package thread;

import java.util.PriorityQueue;

/**
 * @Author liangzai
 * @Description:
 */

class MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;

    public MyTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }
}

class MyTimer{
    private PriorityQueue<MyTask> queue = null;
    private static Object locker = new Object();

    public MyTimer(){
        queue = new PriorityQueue<>(1000);
        Thread thread = new Thread(()->{
            while (true) {
                synchronized (locker){
                    try{
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        long time = queue.peek().getTime();
                        if (time > System.currentTimeMillis()) {
                            locker.wait(time-System.currentTimeMillis());
                            continue;
                        }
                        Runnable runnable = queue.poll().getRunnable();
                        runnable.run();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }

    public void schedule(Runnable runnable, long time){
        synchronized (locker){
            MyTask task = new MyTask(runnable,time+System.currentTimeMillis());
            queue.offer(task);
            locker.notify();
        }
    }
}

public class Demo1 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(()->{
            System.out.println("hello 3000!");
        },3000);
        timer.schedule(()->{
            System.out.println("hello 2000!");
        },2000);
        timer.schedule(()->{
            System.out.println("hello 1000!");
        },1000);

        System.out.println("main 完毕！");
    }
}
